import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintStream;

import parse.Grm;
import parse.Lexer;

import errorMsg.ErrorMsg;

import absyn.Exp;



public class Parser {
	
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.print("Parser error : not enough arguments");
			return;
		}
		
		String filename = args[0];
		ErrorMsg errorMsg = new ErrorMsg(filename);
		InputStream inp;
		java_cup.runtime.Symbol s;
		
		try {
			inp = new FileInputStream(filename);
		} catch (FileNotFoundException e1) {
			System.out.print("Parser error : source file not found");
			return;
		}
		
		Lexer lexer = new Lexer(inp, errorMsg);
		Grm p = new Grm(lexer, errorMsg);
		
		try {
			s = p.parse();
		} catch (Exception e) {
			return;
		}
		
		if (!errorMsg.anyErrors)
		try {
			
			print.Print print = new print.Print(new PrintStream(filename.substring(0, filename.lastIndexOf(".tig")) + ".abs"));
			print.prExp((absyn.Exp)(s.value), 0);
		} catch (Exception e) {
			System.out.print("Parser error : unable to print abstract syntax tree");
			return;
		}
		
		try {
			semant.Semant sm = new semant.Semant(errorMsg);
			sm.transProgram((Exp)s.value);
		} catch (Exception e) {
			System.out.print("Parser error : error occured during generating abstract syntax tree");
			e.printStackTrace();
		}

		if (!errorMsg.anyErrors) System.out.print("parsed successfully, " + filename.substring(0, filename.lastIndexOf(".tig")) + ".abs" + " has been generated.");
	}

}
